<script setup>
import {h, onMounted, ref, resolveDirective, withDirectives} from 'vue'
import {NButton, NForm, NFormItem, NInput, NPopconfirm, NSelect, NTag} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudTable from '@/components/table/CrudTable.vue'

import { useCRUD } from '@/composables'
import api from '@/api'
import {getToken, renderIcon} from "@/utils";
import axios from "axios";
import TheIcon from "@/components/icon/TheIcon.vue";
import CrudModal from "@/components/table/CrudModal.vue";

defineOptions({ name: '报销下载' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '报销下载',
  initForm: {
    args: {
      ping_sleep: 1,
      ping_threshold: 500,
      agent_data_check_threshold: 2,
      agent_incoming_traffic_threshold: 30,
      before_start_clean_sleep: 2,
      before_stop_disposal_sleep: 20,
    },
  },
  doCreate: api.createDownexcelList,
  doUpdate: api.updateHostMonitor,
  doDelete: api.deleteHostMonitor,
  refresh: () => $table.value?.handleSearch(),
})

onMounted(() => {
  $table.value?.handleSearch()
})

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)

  const pad = (num) => num.toString().padStart(2, '0')

  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取当天的开始时间的时间戳
function getStartOfDayTimestamp() {
  const now = new Date()
  now.setHours(0, 0, 0, 0) // 将小时、分钟、秒和毫秒都设置为0
  return now.getTime()
}

// 获取当天的结束时间的时间戳
function getEndOfDayTimestamp() {
  const now = new Date()
  now.setHours(23, 59, 59, 999) // 将小时设置为23，分钟设置为59，秒设置为59，毫秒设置为999
  return now.getTime()
}

// 示例使用
const startOfDayTimestamp = getStartOfDayTimestamp()
const endOfDayTimestamp = getEndOfDayTimestamp()

const datetimeRange = ref([startOfDayTimestamp, endOfDayTimestamp])
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

const data = reactive({
  token: getToken(),
});


async function on_download(row) {
  if (!row.id) return
  row.publishing = true
  row.state = row.state === false
  row.publishing = false
  try {
    let headers = { token: data.token }
    let data_p = { data_id: row.id }
    const response = await axios.get(base_path + 'api/system/downloads/down', {
      responseType: 'blob', // 重要：指定响应类型为 blob
      headers: headers,
      params: data_p,
    })
    // 创建一个新的 URL 对象
    const url = window.URL.createObjectURL(new Blob([response.data]))
    // 创建一个新的链接元素
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', row.name + '.xlsx') // 指定下载文件的名称
    // 模拟点击下载
    document.body.appendChild(link)
    link.click()
    // 清理 URL 对象
    window.URL.revokeObjectURL(url)

    $message?.success('已下载')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.state === false
  } finally {
    row.publishing = false
  }
}

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: '100',
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '文件名称',
    key: 'name',
    width: 400,
    align: 'left',

  },
     {
    title: '生成时间',
    key: 'created_at',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },

    {
    title: '状态',
    key: 'state',
    width: 'auto',
    align: 'center',
      render(row) {
      let state_name = "生成中,请稍后"
        if(row.state===1){
          state_name = "待下载"
        }
        if(row.state===2){
          state_name = "已下载"
        }
      return h(
        NTag,
        { type: row.state===0 ? 'primary' : 'success',bordered:false, style: { margin: '2px 3px' } },
        { default: () => state_name }
      )
    },
  },
      {
    title: '操作',
    key: 'actions',
    width: 180,
    align: 'center',
    fixed: 'right',
    render(row) {
      if(row.state>0){
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                 on_download(row)
              },
            },
            {
              default: () => '下载',
              icon: renderIcon('material-symbols:download', { size: 16 }),
            }
          ),
          []
        )
      ]}
    },
  },

]

const isDisabled = ref(false)
async function addDepts() {
  isDisabled.value = false
  handleAdd()
}



const validateAddUser = {
  start: [
    {
      required: true,
      message: '请输入需要导出的月份',
      trigger: ['input', 'blur', 'change'],
    },
  ],
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage>
    <template #action>
      <div>
        <NButton
          v-permission="'post/api/system/downloads/create'"
          class="float-right mr-15"
          type="primary"
          @click="addDepts"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />
          新建报销导出
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="api.getDownloadsListExcel"
    >
      <template #queryBar>
        <QueryBarItem label="文件名" :label-width="60">
          <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入文件名"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="创建时间" :label-width="70">
          <NDatePicker
            v-model:value="datetimeRange"
            type="datetimerange"
            clearable
            placeholder="请选择时间范围"
            @update:value="handleDateRangeChange"
          />
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal
      v-model:visible="modalVisible"
      title="新建导出报销任务"
      :loading="modalLoading"
      @save="handleSave"
    >
      <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="180"
        :model="modalForm"
        :rules="validateAddUser"
      >
        <NFormItem label="需要导出的月份" path="start">
          <n-date-picker
                        v-model:formatted-value="modalForm.start"
                        value-format="yyyy-MM"
                        type="month"
                        placeholder="导出的月份"
                        style="width: 200px;"
                        clearable
                      />
        </NFormItem>
      </NForm>
    </CrudModal>
  </CommonPage>
</template>

